#!/usr/bin/env node

import { execSync } from 'child_process';
import { readFileSync } from 'fs';
import { join } from 'path';

console.log('🚀 开始发布校验库到NPM...\n');

try {
  // 1. 检查是否已登录
  console.log('1️⃣ 检查NPM登录状态...');
  try {
    const whoami = execSync('npm whoami', { encoding: 'utf8' }).trim();
    console.log(`✅ 已登录为: ${whoami}`);
  } catch (error) {
    console.log('❌ 未登录NPM，请先运行: npm login');
    process.exit(1);
  }

  // 2. 读取package.json
  const packageJson = JSON.parse(readFileSync('package.json', 'utf8'));
  const packageName = packageJson.name;
  
  // 3. 检查包名是否可用
  console.log('\n2️⃣ 检查包名可用性...');
  try {
    execSync(`npm view ${packageName}`, { stdio: 'ignore' });
    console.log(`❌ 包名 ${packageName} 已被占用，请修改package.json中的name字段`);
    process.exit(1);
  } catch (error) {
    console.log(`✅ 包名 ${packageName} 可用`);
  }

  // 4. 构建项目
  console.log('\n3️⃣ 构建项目...');
  execSync('npm run build', { stdio: 'inherit' });
  console.log('✅ 构建完成');

  // 5. 运行测试
  console.log('\n4️⃣ 运行测试...');
  execSync('npm test', { stdio: 'inherit' });
  console.log('✅ 测试通过');

  // 6. 发布到NPM
  console.log('\n5️⃣ 发布到NPM...');
  execSync('npm publish', { stdio: 'inherit' });
  console.log('✅ 发布成功');

  // 7. 验证发布
  console.log('\n6️⃣ 验证发布...');
  const publishedInfo = execSync(`npm view ${packageName}`, { encoding: 'utf8' });
  console.log('✅ 发布验证成功');
  console.log('\n📦 包信息:');
  console.log(publishedInfo);

  console.log('\n🎉 发布完成！');
  console.log(`📦 包名: ${packageName}`);
  console.log(`📋 版本: ${packageJson.version}`);
  console.log(`🔗 安装命令: npm install ${packageName}`);

} catch (error) {
  console.error('\n❌ 发布失败:', error.message);
  process.exit(1);
}
